//
//  MaxAdManager.m
//  HybidMediation
//
//  Created by jay Win on 2019/9/12.
//  Copyright © 2019 jay Win. All rights reserved.
//

#import "MaxAdManager.h"
#import <AppLovinSDK/AppLovinSDK.h>


@interface MaxAdManager()<MAAdDelegate,MARewardedAdDelegate,MAAdViewAdDelegate>
@property (nonatomic, strong) MAAdView *adView;
@property (nonatomic, strong) MAInterstitialAd *interstitialAd;
@property (nonatomic, strong) MARewardedAd *rewardedAd;
@end
@implementation MaxAdManager


#pragma mark   初始化
- (void)initAds:(void (^)(void))succeed{
    [self loadPlacementID];
    [ALSdk shared].mediationProvider=@"max";
//    [[ALSdk shared] showMediationDebugger];
    [[ALSdk shared]initializeSdkWithCompletionHandler:^(ALSdkConfiguration * _Nonnull configuration) {
        succeed();
        if(configuration.consentDialogState==ALConsentDialogStateApplies){
            if(![ALPrivacySettings hasUserConsent]){
                NSLog(@"需要进行GDPR授权");
                  [self.delegate onShowGdpr];
            }
        }else if(configuration.consentDialogState==ALConsentDialogStateDoesNotApply){
             [self agreeGDPR];
        }else{
            
        }
        [self requestInterstitial];
        [self requestRewardVideo];
    }];
}
- (void)loadPlacementID{
    if(iPad&&[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_pad_banner_id"]){
        self.banner_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_pad_banner_id"];
    }else{
        if([[[KKADManager shareInstance]adsConfig]objectForKey:@"max_banner_id"]==nil)
            NSLog(@"max_banner_id为空，请在AdsConfig文件中配置mopub_banner_id字段");
        self.banner_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_banner_id"];
    }
    if(iPad&&[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_pad_interstitial_id"]){
        self.interstitial_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_pad_interstitial_id"];
     }else{
         if([[[KKADManager shareInstance]adsConfig]objectForKey:@"max_interstitial_id"]==nil)
              NSLog(@"max_interstitial_id为空，请在AdsConfig文件中配置max_interstitial_id字段");
         self.interstitial_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_interstitial_id"];
     }
    if(iPad&&[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_pad_rewardVideo_id"]){
        self.reward_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_pad_rewardVideo_id"];
     }else{
         if([[[KKADManager shareInstance]adsConfig]objectForKey:@"max_rewardVideo_id"]==nil)
             NSLog(@"max_rewardVideo_id为空，请在AdsConfig文件中配置max_rewardVideo_id字段");
         self.reward_id=[[[KKADManager shareInstance]adsConfig]objectForKey:@"max_rewardVideo_id"];
     }
}

- (void)agreeGDPR{
   [ALPrivacySettings setHasUserConsent: YES];
}
-(void)agreeCOPPA{
   [ALPrivacySettings setIsAgeRestrictedUser: YES];
}


- (void)showlog:(NSObject *)obj{
    if(self.debug)
        NSLog(@"====MAX=====%@",obj);
}
#pragma mark  banner

#pragma mark - Banner
- (void)showBanner:(UIViewController *)rootViewController bannerContainner:(UIView *)containner{
    self.rootViewController=rootViewController;
    _adView=[[MAAdView alloc]initWithAdUnitIdentifier:self.banner_id];
    [_adView startAutoRefresh];
    _adView.delegate=self;
    CGFloat height = (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) ? 90 : 50;
    // Stretch to the width of the screen for banners to be fully functional
    CGFloat width = CGRectGetWidth(UIScreen.mainScreen.bounds);
    if(IPhoneX){
        _adView.frame = CGRectMake((SCREENWIDTH -width) / 2,
                                   self.isBannerTop?44:SCREENHEIGHT - height-34,
                                   width,height);
    }else {
        _adView.frame = CGRectMake((SCREENWIDTH- width) / 2,
                                   self.isBannerTop?0:SCREENHEIGHT- height,
                                   width,height);
    }
    [containner addSubview:_adView];
    [_adView loadAd];
    [self.delegate onBannerRequest];
}



- (void)showBanner:(UIViewController *)rootViewController bannerContainner:(UIView *)containner isTop:(BOOL)position{
    self.needFixBannerSize=YES;
    self.isBannerTop=position;
    [self showBanner:rootViewController bannerContainner:containner];
}



- (void)showBanner:(UIViewController *)rootViewController bannerUIContainer:(UIView *)container onImpressionEvent:(void (^)(void))onImpression{
    self.onBannerImpression=onImpression;
    [self showBanner:rootViewController bannerContainner:container];
}
- (void)hideBanner{
    if(_adView){
        [_adView removeFromSuperview];
        [_adView stopAutoRefresh];
        _adView=nil;
    }
}
#pragma mark - Banner 回调
- (void)didExpandAd:(MAAd *)ad{
    
}
- (void)didCollapseAd:(MAAd *)ad{
    
}
#pragma mark -插屏
- (void)requestInterstitial{
    if(self.isRequestingInterstitial)
        return;
    self.isRequestingInterstitial=YES;
    if(_interstitialAd==nil){
        _interstitialAd=[[MAInterstitialAd alloc]initWithAdUnitIdentifier: self.interstitial_id];
    }
    _interstitialAd.delegate=self;
    [_interstitialAd loadAd];
    [self.delegate onInterstitialRequest];
}
- (BOOL)hasInterstitial{
    if(_interstitialAd&&[_interstitialAd isReady]){
        return YES;
    }else{
        [self requestInterstitial];
        return NO;
    }
}
- (void)showInterstitial:(UIViewController *)rootViewController{
    if([self hasInterstitial]){
        [self.delegate onInterstitialTrigger];
        [_interstitialAd showAd];
    }else{
        
    }
}
- (void)showInterstitial:(UIViewController *)rootViewController onOpenEvent:(void (^)(void))onOpen onCloseEvent:(void (^)(void))onClose{
    self.onVideoOpen =onOpen;
    self.onVideoClose=onClose;
    [self showInterstitial:rootViewController];
}


#pragma mark - 广告通用回调
- (void)didLoadAd:(MAAd *)ad{
    if(ad.format==MAAdFormat.interstitial){
        self.isRequestingInterstitial=NO;
        [self.delegate onInterstitialLoaded];
    }else if(ad.format==MAAdFormat.rewarded){
        self.isRequestingRewardVideo=NO;
        [self.delegate onRewardVideoLoaded];
    }else if(ad.format==MAAdFormat.banner){
        [self.delegate onBannerLoaded];
        [self.delegate onBannerImpression];
    }else if(ad.format==MAAdFormat.leader){
        [self.delegate onBannerLoaded];
        [self.delegate onBannerImpression];
    }
}
//广告加载失败
- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withErrorCode:(NSInteger)errorCode{
    if(adUnitIdentifier==self.interstitial_id){
        self.isRequestingInterstitial=NO;
        [self.delegate onInterstitialLoadedFailed:[NSString stringWithFormat:@"%ld",(long)errorCode]];
    }else if(adUnitIdentifier==self.reward_id){
        self.isRequestingRewardVideo=NO;
        [self.delegate onRewardVideoLoadedFailed:[NSString stringWithFormat:@"%ld",(long)errorCode]];
        //        [self requestRewardVideo];
    }
    else if(adUnitIdentifier==self.banner_id){
        [self.delegate onBanenrLoadedFailed:[NSString stringWithFormat:@"%ld",(long)errorCode]];
    }
    //延迟3S进行重新加载
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        if(adUnitIdentifier==self.interstitial_id){
            [self requestInterstitial];
        }else if(adUnitIdentifier==self.reward_id){
            [self requestRewardVideo];
        }
    });
}
- (void)didDisplayAd:(MAAd *)ad{
    if(ad.format==MAAdFormat.interstitial){
        if(self.onVideoOpen)
            [self  onVideoOpen];
        [self.delegate onInterstitialOpen];
    }else if(ad.format==MAAdFormat.rewarded){

    }
    else if(ad.format==MAAdFormat.banner){

    }
    else if(ad.format==MAAdFormat.leader){

    }
}
- (void)didClickAd:(MAAd *)ad{
    if(ad.format==MAAdFormat.interstitial){
        [self showlog:@"插屏点击"];
        [self.delegate onInterstitialClick];
    }else if(ad.format==MAAdFormat.rewarded){
        [self showlog:@"激励点击"];
        [self.delegate onRewardVideoClick];
    }
    else if(ad.format==MAAdFormat.banner){
        [self showlog:@"banner点击"];
        [self.delegate onBannerClick];
    }
    else if(ad.format==MAAdFormat.leader){
        [self showlog:@"pad banner点击"];
        [self.delegate onBannerClick];
    }
}

- (void)didHideAd:(MAAd *)ad{
    if(ad.format==MAAdFormat.interstitial){
        [self showlog:@"插屏关闭"];
        [self.delegate onInterstitialClose];
        [self requestInterstitial];
    }else if(ad.format==MAAdFormat.rewarded){
        if(self.completeRewardVideo){
            [self showlog:@"激励完成"];
            if(self.onVideoComplete)
                self.onVideoComplete();
            [self.delegate onRewardVideoComplete];
        }else{
            [self showlog:@"激励中途关闭"];
            if(self.onVideoClose)
                [self onVideoClose];
            [self.delegate onRewardVideoClose];
        }
        [self requestRewardVideo];
    }
}
- (void)didFailToDisplayAd:(MAAd *)ad withErrorCode:(NSInteger)errorCode{
    if(ad.format==MAAdFormat.interstitial){
        [self showlog:@"插屏播放失败"];
        [self.delegate onInterstitialPlayFailed:[NSString stringWithFormat:@"%ld",(long)errorCode]];
    }else if(ad.format==MAAdFormat.rewarded){
        [self showlog:@"激励播放失败"];
        [self.delegate onRewardVideoPlayFailed:[NSString stringWithFormat:@"%ld",(long)errorCode]];
    }
    else if(ad.format==MAAdFormat.banner){
        [self showlog:@"Banner播放失败"];
    }
}
#pragma mark - 激励
- (void)requestRewardVideo{
    if(self.isRequestingRewardVideo)
        return;
    self.completeRewardVideo=NO;
    self.isRequestingRewardVideo=YES;
    if(_rewardedAd==nil){
        _rewardedAd=[MARewardedAd sharedWithAdUnitIdentifier:self.reward_id];
    }
    _rewardedAd.delegate=self;
    [_rewardedAd loadAd];
    [self.delegate onRewardVideoRequest];
}

- (BOOL)hasRewardVideo{
    if(_rewardedAd&&_rewardedAd.isReady){
        return YES;
    }else{
        [self requestRewardVideo];
        return NO;
    }
}
- (void)showRewardVideo:(UIViewController *)rootViewControler onOpenEvent:(void (^)(void))onOpen onCloseEvent:(void (^)(void))onClose onCompleteEvent:(void (^)(void))onComplete{
    self.onVideoOpen =onOpen;
    self.onVideoClose=onClose;
    self.onVideoComplete=onComplete;
    [self showRewardVideo:rootViewControler];
}
- (void)showRewardVideo:(UIViewController *)rootViewController{
    if([self hasRewardVideo]){
        [self.delegate onRewardVideoTrigger];
        [_rewardedAd showAd];
    }else{
        [self showlog:@"激励视频尚未准备好"];
    }
}
#pragma mark - 激励回调
- (void)didStartRewardedVideoForAd:(MAAd *)ad{
    [self showlog:@"激励开始播放"];
}
- (void)didCompleteRewardedVideoForAd:(MAAd *)ad{
    self.completeRewardVideo=YES;
    [self showlog:@"激励视频播放完成"];
    
}
- (void)didRewardUserForAd:(MAAd *)ad withReward:(MAReward *)reward{
    self.completeRewardVideo=YES;
    [self showlog:@"激励发放奖励"];
}
@end

